package com.hm.oauth2.auto;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

/**
 * @author shishun.wang
 * @date 下午3:02:10 2016年11月18日
 * @version 1.0
 * @describe 资源服务器配置
 * 
 *           <note>1.资源服务器 资源服务器承载资源[我们的REST
 *           API]客户端感兴趣的资源位于/user/，@EnableResourceServer注释，在应用的OAuth2资源服务器，
 *           实现了Spring Security的过滤器，使用验证传入的OAuth2令牌的请求。
 *           类ResourceServerConfigurerAdapter实现ResourceServerConfigurer提供的方法来调整由的OAuth2安全保护的访问规则和路径。
 *           </note>
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

	private final static String RESOURCE_ID = "my_res";

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.resourceId(RESOURCE_ID).stateless(false);
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.anonymous().disable()
	        .requestMatchers().antMatchers("/user/**")
	        .and().authorizeRequests()
	        .antMatchers("/user/**").access("hasRole('ADMIN')")
	        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
	}
}
